/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.filterX;

//import acceso.aplicacion.Bulldozer;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wf3.core.Configuration;

/**
 *
 * @author romulogalindo
 */
public class Pasarela implements Filter {

    private FilterConfig filterConfig = null;

    private static boolean filter = true;
    private static String host = "";

    @Override
    public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc)
            throws IOException, ServletException {
        System.out.println("[Pasarela filter]");
        HttpServletRequest request = (HttpServletRequest) sr;
        if (filter) {
            String host_local = request.getHeader("HOST");
            System.out.println("host local: " + host_local);
            if (host_local.contentEquals(host)) {
                fc.doFilter(sr, sr1);
            } else {
                String uri = request.getRequestURI();
                System.out.println("URI: " + uri);
                HttpServletResponse httpResponse = (HttpServletResponse) sr1;
                System.out.println("redireccionando a: " + "http://" + host + uri + "?" + request.getQueryString());
                httpResponse.sendRedirect("http://" + host + uri + "?" + request.getQueryString());
            }
        } else {
            fc.doFilter(sr, sr1);
        }
    }

    /**
     * Return the filter configuration object for this filter.
     *
     * @return
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Destroy method for this filter
     */
    @Override
    public void destroy() {
    }

    /**
     * Init method for this filter
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
//        filter =  ((Bulldozer)filterConfig.getServletContext().getAttribute("acceso")).getWorkflow().isFilter();
//        host =  ((Bulldozer)filterConfig.getServletContext().getAttribute("acceso")).getWorkflow().getHost();
        filter = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).isWf_filter();
        host = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).getWf_filter_host();
        System.out.println("[Pasarela filter: configurado][filter:" + filter + "][host:" + host + "]");
    }

    public synchronized static void update_filter(boolean f, String h) {
        filter = f;
        host = h;
        System.out.println("[Pasarela filter: actualizado][filter:" + filter + "][host:" + host + "]");
    }

}
